<template>
  <div class="root">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list v-model="loading" @load="onLoad" :immediate-check="false" :finished="finished">
        <div
          class="van-hairline--surround"
          style="margin:15px"
          v-for="item in imgList"
          :key="item.id"
          @click="goGoodsInfo(item.id)"
        >
          <img width="157" height="157" v-lazy="item.img_url" />
          <p style="margin: 20px 10px 0px 10px;" class="van-multi-ellipsis--l2">{{item.title }}</p>
          <div class="grayBox">
            <div class="price">
              <span>¥{{item.sell_price}}</span>
            </div>
            <div>
              <van-row type="flex" justify="space-between">
                <van-col span="10">
                  <span>热卖中</span>
                </van-col>
                <van-col span>
                  <span>剩余{{item.stock_quantity}}</span>
                </van-col>
              </van-row>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import Vue from 'vue'
import { Lazyload } from 'vant'
import { mapMutations } from 'vuex'

// options 为可选参数，无则不传
Vue.use(Lazyload)

export default {
  data () {
    return {
      imgList: [],
      isLoading: false,
      loading: false,
      finished: false,
      number: 1
    }
  },
  created () {
    this.getImgList()
  },
  methods: {
    ...mapMutations(['setGoodsListId']),
    async getImgList () {
      const { data: res } = await this.$http.get(
        '/api/getgoods?pageindex=' + this.number
      )
      console.log(res)
      res.message.forEach(item => {
        const index = this.imgList.findIndex(i => i.id === item.id)
        if (index === -1) {
          this.imgList.push(item)
        }
      })
      this.isLoading = false
    },
    onRefresh () {
      this.getImgList()
    },
    onLoad () {
      this.number++
      this.getImgList()
      this.loading = false
      if (this.number++ === 2) {
        this.finished = true
      }
    },
    goGoodsInfo (id) {
      this.$router.push('/goodsinfo')
      this.setGoodsListId(id)
    }
  }
}
</script>
<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
}
.root {
  margin-top: 47px;
}
.van-hairline--surround {
  width: 157px;
  float: left;
  margin-top: 50px;
}
.grayBox {
  padding: 15px;
  background: #ccc;
  .price span {
    color: red;
  }
}
</style>
